package com.zll.onlineExam.activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.LayoutInflaterCompat;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.mikepenz.iconics.context.IconicsLayoutInflater2;
import com.xuexiang.xui.widget.button.roundbutton.RoundButton;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xui.widget.edittext.materialedittext.validation.RegexpValidator;
import com.zll.onlineExam.R;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.db.DBHelper;
import com.zll.onlineExam.utils.XToastUtils;

import java.util.HashMap;
import java.util.Map;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private MaterialEditText mUsername;
    private MaterialEditText mNickname;
    private MaterialEditText mPassword;
    private MaterialEditText mRePassword;
    private RoundButton mButton;
    private Handler mHandler;

    private final int REGISTER_SUCCESS = 1;
    private final int REGISTER_FAIL = 0;
    private final int REGISTER_ERROR = -1;

    private final static String pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)(?!([^(0-9a-zA-Z)])+$).{6,12}$";
    private final static String namePattern = "^[\\u4E00-\\u9FA5A-Za-z0-9_]{4,15}$";
    private static String TAG = "===RegisterActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LayoutInflaterCompat.setFactory2(getLayoutInflater(), new IconicsLayoutInflater2(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
        initListener();
        initHandler();

    }

    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                Intent it;

                switch (msg.what) {
                    case REGISTER_SUCCESS:
                        XToastUtils.success("注册成功，请登录");
                        it = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(it);
                        break;
                    case REGISTER_FAIL:
                        XToastUtils.error("账号已存在");
                        break;
                    case REGISTER_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    default:
                        break;

                }
            }
        };
    }

    private void initView() {
        mUsername = findViewById(R.id.a_reg_username);
        mNickname = findViewById(R.id.a_reg_nickname);
        mPassword = findViewById(R.id.a_reg_password);
        mRePassword = findViewById(R.id.a_reg_repassword);
        mButton = findViewById(R.id.a_reg_b_reg);
    }

    private void initListener() {
        mButton.setOnClickListener(this);

        mUsername.addValidator(new RegexpValidator("用户名格式不对",namePattern));
        mNickname.addValidator(new RegexpValidator("昵称格式不对",namePattern));
        mPassword.addValidator(new RegexpValidator("密码格式不对",pattern));
        mRePassword.addValidator(new RegexpValidator("密码格式不对",pattern));
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.a_reg_b_reg) {
            if (mUsername.validate()
                    && mNickname.validate()
                    && mPassword.validate()
            ) {
                doRegister();
                XToastUtils.info("正在加载");
            }else{
                XToastUtils.error("请先填写好表单");
            }
        }

    }

    private void doRegister() {
        String username = mUsername.getEditValue();
        String nickname = mNickname.getEditValue();
        String password = mPassword.getEditValue();
        String rePassword = mRePassword.getEditValue();

        if (!password.equals(rePassword)){
            XToastUtils.error("两次输入密码不一致");
            return;
        }

        Map<String, Object> data = new HashMap<>();
        data.put("username", username);
        data.put("nickname", nickname);
        data.put("password", password);
        Ajax.post(HTTPConfig.REGISTER, data, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                mHandler.sendEmptyMessage(REGISTER_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(REGISTER_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(REGISTER_ERROR);
            }
        });
    }

}